import { formatDateOfYMD } from "../formatDate/index.js";

const TIMES = new Date();
const YEARY = TIMES.getFullYear();
const MONTH = TIMES.getMonth();
const DAY = TIMES.getDate();
const WEEKDAY = TIMES.getDay();

// 通过今天的时间获取本周开始和结束日期
function getStartAndEndOfWeek() {
  let startDate; //本周的开始日期
  let endDate; //本周的结束日期
  startDate = new Date(YEARY, MONTH, DAY + 1 - WEEKDAY);
  endDate = new Date(YEARY, MONTH, DAY + 7 - WEEKDAY);
  return {
    startDate: formatDateOfYMD(startDate),
    endDate: formatDateOfYMD(endDate),
  };
}

function getStartAndEndOfLastWeek() {
  let startDate; //本周的开始日期
  let endDate; //本周的结束日期
  startDate = new Date(YEARY, MONTH, DAY - 7 + 1 - WEEKDAY);
  endDate = new Date(YEARY, MONTH, DAY - 7 + 7 - WEEKDAY);
  return {
    startDate: formatDateOfYMD(startDate),
    endDate: formatDateOfYMD(endDate),
  };
}

// 通过今天的时间获取本月开始和结束日期
function getStartAndEndOfMonth() {
  let startDate; //本周的开始日期
  let endDate; //本周的结束日期
  startDate = new Date(YEARY, MONTH, 1);
  endDate = new Date(YEARY, MONTH + 1, 0);
  return {
    startDate: formatDateOfYMD(startDate),
    endDate: formatDateOfYMD(endDate),
  };
}

// 通过今天的时间获取上月开始和结束日期
function getStartAndEndOfLastMonth() {
  let startDate; //本周的开始日期
  let endDate; //本周的结束日期
  startDate = new Date(YEARY, MONTH - 1, 1);
  endDate = new Date(YEARY, MONTH, 0);
  return {
    startDate: formatDateOfYMD(startDate),
    endDate: formatDateOfYMD(endDate),
  };
}

//求近N月日期，参数是数字
function getMonthsAgo(monthNum) {
  if (!(typeof monthNum === "number" && monthNum % 1 === 0)) {
    console.error("请输入整数（please enter an integer）");
    return null;
  }
  let date = new Date();
  let year = date.getFullYear();
  let month = date.getMonth() + 1;
  month = month < 10 ? "0" + month : month;
  let day = date.getDate();
  day = day < 10 ? "0" + day : day;
  //days = days.getDate();
  let year2 = year;
  let month2 = parseInt(month) - monthNum;
  if (month2 <= 0) {
    let a = Math.abs(month2); //取绝对值
    year2 =
      parseInt(year2) -
      parseInt(
        monthNum / 12 <= 1
          ? 1
          : a >= 12
          ? Math.ceil(parseInt(monthNum) / 12)
          : Math.floor(parseInt(monthNum) / 12)
      );
    month2 = 12 - (Math.abs(month2) % 12);
  }
  let day2 = day;
  let days2 = new Date(year2, month2, 0);
  days2 = days2.getDate(); //获取当前日期中月的天数 2月只有28
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = "0" + month2;
  }
  let pastTimet = year2 + "-" + month2 + "-" + day2;
  return {
    pastTimet, //过去时间
    presentTime: formatDateOfYMD(new Date()), //当前时间
  };
}

export {
  getStartAndEndOfWeek,
  getStartAndEndOfLastWeek,
  getStartAndEndOfMonth,
  getStartAndEndOfLastMonth,
  getMonthsAgo,
};
